﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.Caching;
using Telerik.Web.UI;
using KPIS.GERP.GIMS.BLL;
using KPIS.GERP.GIMS.IBLL;
using KPIS.GERP.GIMS.MODEL;
using KPIS.GERP.GIMS.DAL;

namespace KPIS.GERP.GIMS.APP.APP_UI.Form
{
    public partial class ICM_ReceiveItem : System.Web.UI.Page
    {
        Common.Main cn = new Common.Main();
        CommandControl cmdFac = new CommandControl();
        ReceiveBLL recBLL = new ReceiveBLL();
        RecevieItemBLL recitemBLL = new RecevieItemBLL();
        AssetBLL assetBLL = new AssetBLL();
        DeliveryNoteBLL dnBLL = new DeliveryNoteBLL();
        DeliveryNoteItemBLL dnitemBLL = new DeliveryNoteItemBLL();        
        MasterDepreciationTypeDAL masDAL = new MasterDepreciationTypeDAL();
        ResourceMasterTypeBLL resmasterBLL = new ResourceMasterTypeBLL();
        ResourceMasterItemBLL resitemBLL = new ResourceMasterItemBLL();
        HrmJobSiteBLL jsBLL = new HrmJobSiteBLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            //cmbDnItem.Attributes.Add("onSelect", "return GetValue();");
             
            if (!Page.IsPostBack)
            {
                CalendarDateExpired.Attributes.Add("onload", "setCalendarTable();return false;");
                lblReceiveSeq.Text = Request.QueryString["ReceiveSeq"].ToString();
                Session["RECEIVESEQ"] = lblReceiveSeq.Text;
                lblDnSeq.Text = Request.QueryString["DnSeq"].ToString();

                LoadRootNodes(RadTreeView1, TreeNodeExpandMode.ServerSideCallBack);
                RadTreeNode selected_node = RadTreeView1.SelectedNode;
                if (selected_node == null)
                {
                    selected_node = RadTreeView1.FindNodeByValue("0");
                    LoadDataGrid();
                }
                LoadUnit();
                LoadcmbDnItem();
            }
            cmbDnItem.Attributes.Add("onSelect", "return GetValue();");
            //hdDnItemSeq.Value = hdDnItemSeq.Value;
        }
        public void LoadDpType()
        {
            IList<M_IcmReceiveObject> infoList = recBLL.GetReceiveObject(Int32.Parse(lblReceiveSeq.Text));
            M_IcmReceiveObject info = new M_IcmReceiveObject();

            bool bVisible = false;

            if (infoList.Count > 0)
            {
                info = infoList[0];

                //bVisible = info.icm_res_type_seq.ToString();
                ResourceMasterTypeInfo mtInfo = new ResourceMasterTypeInfo();
                mtInfo = resmasterBLL.GetResourceMasterType((int)info.icm_res_type_seq);

                bVisible = mtInfo.Depre_cal == "Y";
            }

            RadAjaxPanel1.Visible = bVisible;
        }
        protected void RadTreeView1_NodeExpand(object sender, RadTreeNodeEventArgs e)
        {
            PopulateNodeOnDemand(e, TreeNodeExpandMode.ServerSideCallBack);
        }

        protected void LoadRootNodes(RadTreeView treeView, TreeNodeExpandMode expandMode)
        {
            IBLLTree bll = new TreeBLL();

            foreach (TreeInfo info in bll.GetReceiveItemTreeOnDemand("", Int32.Parse(lblReceiveSeq.Text)))
            {
                RadTreeNode node = new RadTreeNode();
                node.Text = info.Name;
                node.ToolTip = info.Descr;
                node.Value = info.Id;
                node.ImageUrl = info.Image_url;
                if (Convert.ToInt32(info.Children_count) > 0)
                {
                    node.ExpandMode = expandMode;
                }
                treeView.Nodes.Add(node);
            }
        }

        protected void PopulateNodeOnDemand(RadTreeNodeEventArgs e, TreeNodeExpandMode expandMode)
        {
            e.Node.Dispose();
            e.Node.Nodes.Clear();
            IBLLTree bll = new TreeBLL();
            foreach (TreeInfo info in bll.GetReceiveItemTreeOnDemand(e.Node.Value, Int32.Parse(lblReceiveSeq.Text)))
            {
                RadTreeNode node = new RadTreeNode();
                node.Text = info.Name;
                node.ToolTip = info.Descr;
                node.Value = info.Id;
                node.ImageUrl = info.Image_url;
                if (Convert.ToInt32(info.Children_count) > 0)
                {
                    node.ExpandMode = expandMode;
                }
                e.Node.Nodes.Add(node);
            }

            e.Node.Expanded = true;
            e.Node.ExpandMode = expandMode;
        }

        public void PopulateNodeOnEditGrid(RadTreeNodeEventArgs e, TreeNodeExpandMode expandMode)
        {
            IBLLTree bll = new TreeBLL();
            foreach (TreeInfo info in bll.GetReceiveItemTreeOnDemand(e.Node.Value, Int32.Parse(lblReceiveSeq.Text)))
            {
                RadTreeNode node = new RadTreeNode();
                node.Text = info.Name;
                node.ToolTip = info.Descr;
                node.Value = info.Id;
                node.ImageUrl = info.Image_url;
                if (Convert.ToInt32(info.Children_count) > 0)
                {
                    node.ExpandMode = expandMode;
                }
                e.Node.Nodes.Add(node);
            }
            e.Node.Nodes.Clear();
            e.Node.ExpandMode = expandMode;
        }

        protected void btnExpand_Click(object sender, ImageClickEventArgs e)
        {
            IBLLTree bll = new TreeBLL();
            RadTreeView1.Nodes.Clear();
            RadTreeView1.DataSource = bll.GetReceiveItemTree();
            RadTreeView1.DataBind();
            RadTreeView1.ExpandAllNodes();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            IBLLTree bll = new TreeBLL();
            RadTreeView1.Nodes.Clear();
            if (txtSearch.Text.Length > 0)
            {
                RadTreeView1.DataSource = bll.GetResourceMasterTreeResultSearch(txtSearch.Text);
                RadTreeView1.DataBind();
                RadTreeView1.ExpandAllNodes();
                lblResult.Text = RadTreeView1.GetAllNodes().Count.ToString();
                PanelSearch.Visible = true;
            }
            else
            {
                LoadRootNodes(RadTreeView1, TreeNodeExpandMode.ServerSideCallBack);
                PanelSearch.Visible = false;
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            IBLLTree bll = new TreeBLL();
            RadTreeView1.Nodes.Clear();
            LoadRootNodes(RadTreeView1, TreeNodeExpandMode.ServerSideCallBack);
            PanelSearch.Visible = false;
        }

        protected void RadTreeView1_NodeClick(object sender, RadTreeNodeEventArgs e)
        {
            RadTreeNode selected_node = RadTreeView1.SelectedNode;
            string value = selected_node.Value;
            string[] node_text = selected_node.Text.Split(new string[] { " - " }, StringSplitOptions.None);
            string[] all_value = value.Split('-');

            Session["ParentID"] = value;
            LoadDataGrid();

            //if (all_value.Length == 1)
            //{
            //    if (all_value[0] == "0")
            //    {
            //        LoadDataGrid();
            //        ReceiveItemControl1.Visible = true;
            //    }
            //    else
            //    {
            //        Session["TypeSeq"] = all_value[0];
            //        //ResourceGroupControl1.SetHeader(node_text[1]);
            //        //ResourceGroupControl1.LoadDataGrid();
            //        //ResourceGroupControl1.Visible = true;
            //    }
            //}
            
            //else 
            //{
            //    BlankTreeControl1.Visible = true;
            //    BlankTreeControl1.SetHeader("การบันทึกโครงสร้างการจำแนกพัสดุ บันทึกได้ถึงระดับรายการพัสดุเท่านั้น");
            //}
        }

        protected void btnCollapse_Click(object sender, EventArgs e)
        {
            RadTreeView1.CollapseAllNodes();
        }

        protected void RadManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            if (e.Argument == "CloseWindow")
            {
                RefreshTree();
            }
            else
            {
                GetKeyValue(e.Argument);
            }
        }

        public void RefreshTree()
        {
            RadTreeNode selected_node = RadTreeView1.SelectedNode;
            if (selected_node == null)
            {
                selected_node = RadTreeView1.FindNodeByValue("0");
            }
            RadTreeNodeEventArgs node = new RadTreeNodeEventArgs(selected_node);
            RadManager1.ResponseScripts.Add(@"CollapseSelectTree();");
            PopulateNodeOnEditGrid(node, TreeNodeExpandMode.ServerSideCallBack);
            RadManager1.ResponseScripts.Add(@"ExpandSelectTree();");
        }

        public void LoadDataGrid()
        {
            IList<ReceiveItemInfo> info = recitemBLL.GetReceiveItems((int?)null, Convert.ToInt32(lblReceiveSeq.Text), "");
            Grid.DataSource = info;
            Grid.DataBind();

            cmdFac.GridCommand(panelList, panelGrid, panelCommand);
        }

        private void LoadUnit()
        {
            IBLLMasterUnit unit = new MasterUnitBLL();
            IList<MasterUnitInfo> info = unit.GetMasterUnit();
            cmbUnit.DataSource = info;
            cmbUnit.DataBind();
        }
        public bool GetAutoJobSite()
        {
            IList<M_IcmReceiveObject> infoList = recBLL.GetReceiveObject(Convert.ToInt32(lblReceiveSeq.Text));
            M_IcmReceiveObject recInfo = new M_IcmReceiveObject();

            bool bVisible = false;

            if (infoList.Count > 0)
            {
                recInfo = infoList[0];
                bVisible = !string.IsNullOrEmpty(recInfo.job_site_seq.ToString());
            }
            return bVisible;
        }
        public bool GetDeliveryNode()
        {
            IList<M_IcmReceiveObject> infoList = recBLL.GetReceiveObject(Convert.ToInt32(lblReceiveSeq.Text));
            M_IcmReceiveObject recInfo = new M_IcmReceiveObject();

            bool bVisible = false;

            if (infoList.Count > 0)
            {
                recInfo = infoList[0];
                bVisible = !string.IsNullOrEmpty(recInfo.icm_dn_seq.ToString());
            }
            return bVisible;
        }
        public void GetKeyValue(string seq)
        {
            if (seq.Length > 0)
            {
                ReceiveItemInfo itemInfo = new ReceiveItemInfo();
                //IList<M_IcmReceiveObject> rInfo = new M_IcmReceiveObject();
                //rInfo = recBLL.GetReceiveObject(Int32.Parse(lblReceiveSeq.Text));

                IList<ReceiveItemInfo> info = recitemBLL.GetReceiveItems(Int32.Parse(seq), (int?)null, "");

                if (info.Count > 0)
                {
                    itemInfo = info[0];

                    cmbDnItem.Items.Add(new RadComboBoxItem(itemInfo.DeliveryNoteItem.Descr, itemInfo.DeliveryNoteItem.Seq.ToString()));
                    cmbDnItem.SelectedValue = itemInfo.DeliveryNoteItem.Seq.ToString();

                    cmbResItem.Items.Add(new RadComboBoxItem(itemInfo.ResourceItemSeq.Name, itemInfo.ResourceItemSeq.Seq.ToString()));
                    cmbResItem.SelectedValue = itemInfo.ResourceItemSeq.Seq.ToString();

                    cmbToJobSite.Items.Add(new RadComboBoxItem(itemInfo.JobSiteSeq.Name, itemInfo.JobSiteSeq.Seq.ToString()));
                    cmbToJobSite.SelectedValue = itemInfo.JobSiteSeq.Seq.ToString();

                    LoadDpType();
                    cmbDepreciationType.Items.Add(new RadComboBoxItem(itemInfo.DepreciationType.Name, itemInfo.DepreciationType.Seq.ToString()));
                    cmbDepreciationType.SelectedValue = itemInfo.DepreciationType.Seq.ToString();
                 
                    txtSerialNumber.Text = itemInfo.SerialNumber;
                    txtDescr.Text = itemInfo.Description;
                    txtAccessary.Text = itemInfo.Accessary;
                    txtQty.Text = itemInfo.Quantity.ToString();
                    txtPrice.Text = itemInfo.UnitPrice.ToString();
                    txtDateExpired.Text = itemInfo.DateExpired.ToString();
                    txtRemark.Text = itemInfo.Remark;
                    if (itemInfo.ResourceItemSeq.InfoUnit == null)
                    {
                        cmbUnit.SelectedIndex = -1;
                        cmbUnit.Text = string.Empty;
                    }
                    else
                        cmbUnit.SelectedValue = itemInfo.ResourceItemSeq.InfoUnit.Seq.ToString();

                    cmdFac.ViewCommand(panelList, panelGrid, panelCommand);
                    AjaxPanelDnItem.Visible = GetDeliveryNode();
                    AjaxPanelAutoJobSite.Visible = GetAutoJobSite();

                    cmdFac.SetPanel(AjaxPanelDnItem, "View");
                    cmdFac.SetAjaxPanel(AjaxPanelAutoJobSite, "View");
                    PanelPhoto.Visible = false;
                    hdChangeFile.Value = "";
                }
            }
        }

        protected void AddNew_Click(object sender, EventArgs e)
        {
            cmdFac.AddNewCommand(panelList, panelGrid, panelCommand);
            txtSerialNumber.Visible = false;
            LoadDpType();
            PanelPhoto.Visible = true;
            imgPhoto.ImageUrl = SystemInfo._EmptyImage;
            hdChangeFile.Value = "";
            //((HiddenField)this.Parent.FindControl("hdChangeFile")).Value = "";
        }

        protected void Edit_Click(object sender, EventArgs e)
        {
            cmdFac.EditCommand(panelList, panelGrid, panelCommand);
            txtSerialNumber.Visible = true;
            PanelPhoto.Visible = true;
        }

        protected void Delete_Click(object sender, EventArgs e)
        {
            IList<ReceiveItemInfo> infoList = new List<ReceiveItemInfo>();
            if (panelGrid.Visible)
            {
                foreach (GridDataItem data in Grid.MasterTableView.GetSelectedItems())
                {
                    ReceiveItemInfo info = new ReceiveItemInfo();
                    info.Seq = Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Seq"]);
                    info.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());

                    infoList.Add(info);
                }
            }
            else
            {
                ReceiveItemInfo info = new ReceiveItemInfo();

                info.Seq = Convert.ToInt32(((HiddenField)this.Parent.FindControl("hdSeq")).Value);
                info.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());

                infoList.Add(info);
            }

            if (infoList.Count == 0)
            {
                RadManager1.Alert(SystemInfo._DeleteNull);
                return;
            }

            try
            {
                recitemBLL.DeleteAll(infoList);
                RefreshTree();
            }
            catch
            {
                RadManager1.Alert(SystemInfo._DeleteError);
                return;
            }

            LoadDataGrid();
        }

        protected void AddNewSave_Click(object sender, EventArgs e)
        {
            ReceiveItemInfo info = new ReceiveItemInfo();
            M_IcmReceiveObject rcInfo = new M_IcmReceiveObject();
            ResourceMasterItemInfo resInfo = new ResourceMasterItemInfo();
            MasterUnitInfo infoUnit = new MasterUnitInfo();
            ImageInfo infoImage = new ImageInfo();
            DeliveryNoteItemInfo dnitemInfo = new DeliveryNoteItemInfo();
            MasterDepreciationTypeInfo dpinfo = new MasterDepreciationTypeInfo();
            RecordInfo infoRecord = new RecordInfo();
            HrmJobSiteInfo jsInfo = new HrmJobSiteInfo();
            string source_file = hdSourceFile.Value;
            string strMonth = DateTime.Today.Month.ToString();
            string strYear = DateTime.Today.Year.ToString();
            string lastNumber = "";

            if (source_file.Length > 0)
            {
                FileInfo fiSource = new FileInfo(source_file);
                infoImage.File_info = fiSource;
            }
            int ReceiveSeq = Convert.ToInt32(lblReceiveSeq.Text);
            rcInfo.icm_receive_seq = ReceiveSeq;
            info.ReceiveSeq = rcInfo;
            dnitemInfo.Seq = cn.ConvertNullInt(cmbDnItem.SelectedValue);
            info.DeliveryNoteItem = dnitemInfo;
            resInfo.Seq = cn.ConvertNullInt(cmbResItem.SelectedValue);
            info.ResourceItemSeq = resInfo;
            jsInfo.Seq = cn.ConvertNullInt(cmbToJobSite.SelectedValue);
            info.JobSiteSeq = jsInfo;
            dpinfo.Seq = cn.ConvertNullInt(cmbDepreciationType.SelectedValue);
            info.DepreciationType = dpinfo;
            info.LotNumber = "";
            info.SerialNumber = txtSerialNumber.Text;
            info.UpperItemSeq = Session["ParentID"] == null ? (int?)null : cn.ConvertNullInt(Session["ParentID"].ToString());
            info.DateExpired = string.IsNullOrEmpty(txtDateExpired.Text) ? (DateTime?)null : cn.ConvertNullDateTime(txtDateExpired.TextWithLiterals);
            info.Description = txtDescr.Text.Trim();
            info.Accessary = txtAccessary.Text.Trim();
            info.Quantity = Int32.Parse(txtQty.Text);
            info.UnitPrice = Convert.ToDouble(txtPrice.Text);
            info.Remark = txtRemark.Text.Trim();
            info.Created_by = Int32.Parse(Session["EmpSeq"].ToString());

            try
            {   
                lastNumber = recitemBLL.InsertReturnSerialNo(info);

                AssetInfo asInfo = new AssetInfo();

                asInfo.Code = strYear + strMonth + "-" + lastNumber;
                asInfo.Name = cmbResItem.Text.Trim();
                asInfo.AssetDate = DateTime.Today;
                asInfo.SerialNumber = lastNumber;
                asInfo.Remarks = "";
                asInfo.DepreciateBelowFlag = 1;
                asInfo.Price = string.IsNullOrEmpty(txtPrice.Text.Trim()) ? 0 : double.Parse(txtPrice.Text.Trim());
                asInfo.ResourceItemInfo = resInfo;
                asInfo.ReceiveInfo = rcInfo;
                asInfo.Created_by = Int32.Parse(Session["EmpSeq"].ToString());
                
                assetBLL.Insert(asInfo);

                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "onclick", "MessageAlert('เลขที่พัสดุคือ : " + lastNumber + "')", true);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }
            //RadManager1.Alert("เลขที่พัสดุ : '" + lastNumber + "'");

            //RadManager1.ResponseScripts.Add(@"CloseWindow();");

            LoadDataGrid();
            RefreshTree();
        }

        protected void EditSave_Click(object sender, EventArgs e)
        {
            ReceiveItemInfo info = new ReceiveItemInfo();
            M_IcmReceiveObject rcInfo = new M_IcmReceiveObject();
            ResourceMasterItemInfo resInfo = new ResourceMasterItemInfo();
            MasterUnitInfo infoUnit = new MasterUnitInfo();
            ImageInfo infoImage = new ImageInfo();
            DeliveryNoteItemInfo dnitemInfo = new DeliveryNoteItemInfo();
            MasterDepreciationTypeInfo dpinfo = new MasterDepreciationTypeInfo();
            RecordInfo infoRecord = new RecordInfo();
            HrmJobSiteInfo jsInfo = new HrmJobSiteInfo();
            string source_file = hdSourceFile.Value;
            if (source_file.Length > 0)
            {
                FileInfo fiSource = new FileInfo(source_file);
                infoImage.File_info = fiSource;
            }

            info.Seq = Convert.ToInt32(hdSeq.Value);
            dnitemInfo.Seq = cn.ConvertNullInt(cmbDnItem.SelectedValue);
            info.DeliveryNoteItem = dnitemInfo;
            resInfo.Seq = cn.ConvertNullInt(cmbResItem.SelectedValue);
            info.ResourceItemSeq = resInfo;
            jsInfo.Seq = cn.ConvertNullInt(cmbToJobSite.SelectedValue);
            info.JobSiteSeq = jsInfo;
            dpinfo.Seq = cn.ConvertNullInt(cmbDepreciationType.SelectedValue);
            info.DepreciationType = dpinfo;
            info.LotNumber = "";
            info.SerialNumber = txtSerialNumber.Text.Trim();
            info.UpperItemSeq = Session["ParentID"] == null ? (int?)null : cn.ConvertNullInt(Session["ParentID"].ToString());
            info.DateExpired = string.IsNullOrEmpty(txtDateExpired.Text) ? (DateTime?)null : cn.ConvertNullDateTime(txtDateExpired.TextWithLiterals);
            info.Description = txtDescr.Text.Trim();
            info.Accessary = txtAccessary.Text.Trim();
            info.Quantity = Int32.Parse(txtQty.Text);
            info.UnitPrice = Convert.ToDouble(txtPrice.Text);
            info.Remark = txtRemark.Text.Trim();
            info.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());

            try
            {
                recitemBLL.Update(info);

                AssetInfo asInfo = new AssetInfo();

                //asInfo.Code = strYear + strMonth + "-" + lastNumber;
                asInfo.Name = cmbResItem.Text.Trim();
                asInfo.AssetDate = DateTime.Today;
                asInfo.SerialNumber = txtSerialNumber.Text.Trim();
                asInfo.Remarks = "";
                asInfo.DepreciateBelowFlag = 1;
                asInfo.Price = string.IsNullOrEmpty(txtPrice.Text.Trim()) ? 0 : double.Parse(txtPrice.Text.Trim());
                asInfo.ResourceItemInfo = resInfo;
                asInfo.ReceiveInfo = rcInfo;
                asInfo.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());

                assetBLL.Update(asInfo);

                RefreshTree();
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }
            cmdFac.ViewCommand(panelList, panelGrid, panelCommand);
            PanelPhoto.Visible = false;
            //if (info.Image_name.Length > 0)
            //{
            //    imgPhoto.ImageUrl = (info.Image_name.Length > 0
            //            ? SystemInfo._ImagePath + info.Image_name + "?n=" + DateTime.Now.ToString()
            //            : SystemInfo._EmptyImage + "?n=" + DateTime.Now.ToString());
            //}
            //else
            //{
            //    imgPhoto.ImageUrl = (itemInfo.Image_name.Length > 0
            //            ? SystemInfo._ImagePath + itemInfo.Image_name + "?n=" + DateTime.Now.ToString()
            //            : SystemInfo._EmptyImage + "?n=" + DateTime.Now.ToString());
            //}
        }

        protected void Cancel_Click(object sender, EventArgs e)
        {
            cmdFac.CancelCommand(panelList, panelGrid, panelCommand);
            PanelPhoto.Visible = false;
        }

        protected void ShowGrid_Click(object sender, EventArgs e)
        {
            LoadDataGrid();
        }

        protected void Grid_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "DataDelete")
            {
                int seq = Convert.ToInt32((e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Seq"]);                
                recitemBLL.Delete(seq, Convert.ToInt32(Session["EmpSeq"]));
                RefreshTree();
            }
            LoadDataGrid();
        }

        protected void clearFilter_Click(object sender, EventArgs e)
        {
            foreach (GridColumn column in Grid.MasterTableView.Columns)
            {
                column.CurrentFilterFunction = GridKnownFunction.NoFilter;
                column.CurrentFilterValue = string.Empty;
            }
            Grid.MasterTableView.FilterExpression = string.Empty;
            LoadDataGrid();
        }
        private static string GetStatusMessage(int offset, int total)
        {
            if (total <= 0)
                return "ไม่มีข้อมูล";

            return String.Format("รายการที่ <b>1</b>-<b>{0}</b> จากทั้งหมด <b>{1}</b> รายการ", offset, total);
        }
        private void LoadcmbDnItem()
        {
            IList<DeliveryNoteItemInfo> infoList = dnitemBLL.GetDeliveryNoteItemWithParent(Int32.Parse(lblDnSeq.Text));
            cmbDnItem.DataSource = infoList;
            cmbDnItem.DataBind();

            cmbDnItem.Items.Insert(0, new RadComboBoxItem("<เลือกรายการ>", ""));
            cmbDnItem.SelectedIndex = 0;
        }
        //protected void cmbDnItem_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        //{
        //    IList<DeliveryNoteItemInfo> infoList = dnitemBLL.GetDeliveryNoteItemWithParent(Int32.Parse(lblDnSeq.Text));

        //    int itemOffset = e.NumberOfItems;
        //    int endOffset = Math.Min(itemOffset + 10, infoList.Count);
        //    e.EndOfItems = (endOffset == infoList.Count);

        //    cmbDnItem.DataSource = infoList;
        //    cmbDnItem.DataBind();
        //    //int j = 0;
        //    //for (int i = itemOffset; i < endOffset; i++)
        //    //{
        //    //    cmbDnItem.Items.Add(new RadComboBoxItem(infoList[i].Descr, infoList[i].Seq.ToString()));

        //    //    TableRow tr = new TableRow();

        //    //    TableCell tdCode = new TableCell();
        //    //    Label lblCode = new Label();
        //    //    lblCode.Text = infoList[i].Seq.ToString();
        //    //    tdCode.Width = Unit.Pixel(150);
        //    //    tdCode.Controls.Add(lblCode);
        //    //    tr.Cells.Add(tdCode);

        //    //    TableCell tdName = new TableCell();
        //    //    Label lblName = new Label();
        //    //    lblName.Text = infoList[i].Descr;
        //    //    tdName.Width = Unit.Pixel(250);
        //    //    tdName.Controls.Add(lblName);
        //    //    tr.Cells.Add(tdName);

        //    //    ((Table)cmbDnItem.Items[j].FindControl("tableDnItem")).Controls.Add(tr);
        //    //    j++;
        //    //}

        //    e.Message = GetStatusMessage(endOffset, infoList.Count);
        //}

        //protected void cmbDnItem_ItemDataBound(object sender, RadComboBoxItemEventArgs e)
        //{
        //    e.Item.Text = ((DeliveryNoteItemInfo)e.Item.DataItem).Descr;
        //    e.Item.Value = ((DeliveryNoteItemInfo)e.Item.DataItem).Seq.ToString();
        //}

        protected void cmbResItem_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        {            
            Nullable<int> DnItemSeq = string.IsNullOrEmpty(hdDnItemSeq.Value) ? (int?)null : Int32.Parse(hdDnItemSeq.Value);
            Nullable<int> ResTypeSeq = 1;
            IList<DeliveryNoteItemInfo> infoList = dnitemBLL.GetResourceItemDeliveryNoteItem(DnItemSeq);
            IList<ResourceMasterItemInfo> resInfo = resitemBLL.GetResourceMasterItem((int?)null, ResTypeSeq, e.Text);

            if (DnItemSeq.HasValue)
            {
                int itemOffset = e.NumberOfItems;
                int endOffset = Math.Min(itemOffset + 10, infoList.Count);
                e.EndOfItems = (endOffset == infoList.Count);
                int j = 0;
                for (int i = itemOffset; i < endOffset; i++)
                {
                    cmbResItem.Items.Add(new RadComboBoxItem(infoList[i].InfoPoInstallItem.InfoBidderQuotation.InfoPrItem.InfoItem.Name, infoList[i].InfoPoInstallItem.InfoBidderQuotation.InfoPrItem.InfoItem.Seq.ToString()));

                    TableRow tr = new TableRow();

                    TableCell tdCode = new TableCell();
                    Label lblCode = new Label();
                    lblCode.Text = infoList[i].InfoPoInstallItem.InfoBidderQuotation.InfoPrItem.InfoItem.Code;
                    tdCode.Width = Unit.Pixel(150);
                    tdCode.Controls.Add(lblCode);
                    tr.Cells.Add(tdCode);

                    TableCell tdName = new TableCell();
                    Label lblName = new Label();
                    lblName.Text = infoList[i].InfoPoInstallItem.InfoBidderQuotation.InfoPrItem.InfoItem.Name;
                    tdName.Width = Unit.Pixel(250);
                    tdName.Controls.Add(lblName);
                    tr.Cells.Add(tdName);

                    ((Table)cmbResItem.Items[j].FindControl("tableResItem")).Controls.Add(tr);
                    j++;
                }

                e.Message = GetStatusMessage(endOffset, infoList.Count);
            }
            else 
            {
                int itemOffset = e.NumberOfItems;
                int endOffset = Math.Min(itemOffset + 10, resInfo.Count);
                e.EndOfItems = (endOffset == resInfo.Count);
                int j = 0;
                for (int i = itemOffset; i < endOffset; i++)
                {
                    cmbResItem.Items.Add(new RadComboBoxItem(resInfo[i].Name, resInfo[i].Seq.ToString()));

                    TableRow tr = new TableRow();

                    TableCell tdCode = new TableCell();
                    Label lblCode = new Label();
                    lblCode.Text = resInfo[i].Code;
                    tdCode.Width = Unit.Pixel(150);
                    tdCode.Controls.Add(lblCode);
                    tr.Cells.Add(tdCode);

                    TableCell tdName = new TableCell();
                    Label lblName = new Label();
                    lblName.Text = resInfo[i].Name;
                    tdName.Width = Unit.Pixel(250);
                    tdName.Controls.Add(lblName);
                    tr.Cells.Add(tdName);

                    ((Table)cmbResItem.Items[j].FindControl("tableResItem")).Controls.Add(tr);
                    j++;
                }

                e.Message = GetStatusMessage(endOffset, resInfo.Count);
            }
        }
        protected void cmbToJobSite_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        {
            // By KHIM *********************************************
            IList<HrmJobSiteInfo> infoList = jsBLL.GetJobSite(e.Text);

            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + 10, infoList.Count);
            e.EndOfItems = (endOffset == infoList.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cmbToJobSite.Items.Add(new RadComboBoxItem(infoList[i].Name, infoList[i].Seq.ToString()));

                TableRow tr = new TableRow();

                TableCell tdName = new TableCell();
                Label lblName = new Label();
                lblName.Text = infoList[i].Name;
                tdName.Width = Unit.Pixel(250);
                tdName.Controls.Add(lblName);
                tr.Cells.Add(tdName);
                ((Table)cmbToJobSite.Items[j].FindControl("tableToJobSite")).Controls.Add(tr);
                j++;
            }

            e.Message = GetStatusMessage(endOffset, infoList.Count);
        }
        protected void cmbDepreciationType_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        {
            IList<MasterDepreciationTypeInfo> infoList = masDAL.GetMasterDepreciationType();
            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + 10, infoList.Count);
            e.EndOfItems = (endOffset == infoList.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cmbDepreciationType.Items.Add(new RadComboBoxItem(infoList[i].Name.ToString(), infoList[i].Seq.ToString()));
                TableRow tr = new TableRow();
                TableCell tdCode = new TableCell();
                Label lblCode = new Label();
                lblCode.Text = infoList[i].Name.ToString();
                tdCode.Width = Unit.Pixel(200);
                tdCode.Controls.Add(lblCode);
                tr.Cells.Add(tdCode);
 
                ((Table)cmbDepreciationType.Items[j].FindControl("tableDepreciationType")).Controls.Add(tr);
                j++;
            }

            e.Message = GetStatusMessage(endOffset, infoList.Count);

        }

        protected void cmbDnItem_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            hdDnItemSeq.Value = cmbDnItem.SelectedValue;
        }

        protected void btnSelectDN_Click(object sender, EventArgs e)
        {
            hdDnItemSeq.Value = cmbDnItem.SelectedValue;
        }
    }
}
